using System;
using System.Collections.Generic;
using System.IO.Pipes;
using System.Text;

namespace VisualGTest.Binding
{
    /// <summary>
    /// Supports reading messages from a pipe stream.
    /// </summary>
    class PipeMessageReader
    {
        private ByteBuffer m_message;
        private byte[] m_buffer;

        public PipeMessageReader()
        {
            m_message = new ByteBuffer();
            m_buffer = new byte[ByteBuffer.BUFFER_CAPACITY];
        }

        /// <summary>
        /// Reads a message synchronously from the pipe, and returns a byte
        /// array sized precisely for its content. Returns null if no message
        /// could be read.
        /// </summary>
        /// <param name="pipeStream">the stream from which to read the message
        /// </param>
        public byte[] ReadMessageBytes(PipeStream pipeStream)
        {
            if (! pipeStream.IsConnected || ! pipeStream.CanRead)
            {
                return null;
            }

            int bytesRead;

            m_message.Clear();

            do
            {
                bytesRead = pipeStream.Read(m_buffer, 0, m_buffer.Length);
                m_message.Append(m_buffer, bytesRead);
            } while (!pipeStream.IsMessageComplete);

            return m_message.Bytes;
        }
    }
}
